/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vn.edu.vttu;

import java.awt.Color;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lucas Nguyen
 */
public class MainLayer extends javax.swing.JFrame {

    /**
     * Creates new form MainLayer
     */
    
   /*      modelHopThuDen.addRow (new String []{
                                   "<html><body><b>" + msg.getSubject()+"<html><body><b>" ,
                                    "<html><body><b>" +msg.getFrom()[0].toString()+"<html><body><b>" ,
                                    "<html><body><b>" +msg.getContentType()+"<html><body><b>" ,
                                    msg.getSentDate().toString(),
                                    "<html><body><b>" +msg.getSentDate()+"<html><body><b>" ,
                                  msg.isSet(Flags.Flag.SEEN) ? "Đã đọc" : "Chưa đọc"
    
                                });// danh sách thư*/
    
    
		
                String mailPop3Host = "nhom5.no-ip.org";
		String mailStoreType = "pop3";
		String mailUser = "hoangthach@nhom5.no-ip.org";
                String mailPassword = "1";           
                  ImageIcon dinhKem = new ImageIcon("../N547.png");
                  int unReadMessge ;
  //   private DefaultTableModel modelHopThuDen;            
     private Vector<Message> message;
     private   DefaultTableModel loadHopThuDen;
      
    public MainLayer() {
        initComponents();
    //     model = new DefaultTableModel();
        /*   modelHopThuDen = new DefaultTableModel(null, new String[]{ "Chủ đề","Người gửi", "Tóm tắt nội dung","Dispo", "Ngày gửi","Kích thước","Tình trạng"}) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
             tbdsthu.setModel(modelHopThuDen);// cài đặt bảng*/
      //  loadMail();
         Vector<String> header = new Vector<String>();
         header.add("File đính kèm");
         header.add("Chủ đề");
         header.add("Người gửi");
         header.add("Người nhận");
         header.add("Nội dung");
         header.add("Ngày gửi");
         header.add("Kích thước");
            loadHopThuDen = new DefaultTableModel(null, header) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
            tbdsthu.setModel(loadHopThuDen);// cài đặt bảng*/
        loadnoidung.setEnabled(false);
        lbchude.setText(" ");
        lbnguoigui.setText(" ");
        lbngaygui.setText(" ");
     
     //   lbnoidung.setText("Nội dung: ");
      //   loadmail.setBackground(Color.RED);
        readMultipartMail();
        teanoidungmail.setEditable(false);
        btsoanthu.setEnabled(true);
      //  taiFile.setVisible(false);
        tenFile.setText("");
      bttaifile.setVisible(false);
      downLoadFile.setVisible(false);
     if(loadHopThuDen.getRowCount()>0)
     btxoathu.setEnabled(true);  
     else 
         btxoathu.setEnabled(false);
    }

     
       
        
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbdsthu = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        btsoanthu = new javax.swing.JButton();
        bthopthuden = new javax.swing.JButton();
        btthoat = new javax.swing.JButton();
        btxoathu = new javax.swing.JButton();
        loadnoidung = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        lbnguoigui = new javax.swing.JLabel();
        lbchude = new javax.swing.JLabel();
        lbngaygui = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        teanoidungmail = new javax.swing.JTextArea();
        taiFile = new javax.swing.JPanel();
        bttaifile = new javax.swing.JButton();
        tenFile = new javax.swing.JLabel();
        downLoadFile = new javax.swing.JProgressBar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jbtlaythu = new javax.swing.JMenu();
        jbtsoanthu = new javax.swing.JMenu();
        jMenu1 = new javax.swing.JMenu();
        UIPlasticXP = new javax.swing.JMenuItem();
        UIPlastic3D = new javax.swing.JMenuItem();
        UIPlastic = new javax.swing.JMenuItem();
        UIWindows = new javax.swing.JMenuItem();
        jbttrogiup = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jbtthoatchuongtrinh = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));
        jLabel1.setText("Chào mừng đến với hộp thư Htmail");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(312, 312, 312)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbdsthu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbdsthu.setGridColor(new java.awt.Color(255, 204, 204));
        tbdsthu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbdsthuMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbdsthu);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 8, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btsoanthu.setBackground(new java.awt.Color(204, 204, 255));
        btsoanthu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/256px-Email_Shiny_Icon.svg.png"))); // NOI18N
        btsoanthu.setText("  Soạn thư mới");
        btsoanthu.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btsoanthu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btsoanthuActionPerformed(evt);
            }
        });

        bthopthuden.setBackground(new java.awt.Color(204, 255, 204));
        bthopthuden.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        bthopthuden.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon_homea[1].png"))); // NOI18N
        bthopthuden.setText("   Hộp thư đến");
        bthopthuden.setActionCommand("  Hộp thư đến");
        bthopthuden.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        bthopthuden.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        bthopthuden.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bthopthudenActionPerformed(evt);
            }
        });

        btthoat.setBackground(new java.awt.Color(255, 204, 204));
        btthoat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/reboot lodo.jpg"))); // NOI18N
        btthoat.setText("   Thoát");
        btthoat.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btthoat.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btthoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btthoatActionPerformed(evt);
            }
        });

        btxoathu.setBackground(new java.awt.Color(0, 255, 204));
        btxoathu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon_xalo.png"))); // NOI18N
        btxoathu.setText("  Xóa thư");
        btxoathu.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btxoathu.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btxoathu.setInheritsPopupMenu(true);
        btxoathu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btxoathuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btthoat, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bthopthuden, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btsoanthu, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btxoathu, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(btsoanthu, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(bthopthuden, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(btxoathu, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(btthoat, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        loadnoidung.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        loadnoidung.setToolTipText("Thông tin chi tiết");

        jPanel4.setBackground(new java.awt.Color(0, 255, 255));
        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lbnguoigui.setText("Người gửii");

        lbchude.setBackground(new java.awt.Color(51, 204, 255));
        lbchude.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lbchude.setText("Chủ đề:");

        lbngaygui.setBackground(new java.awt.Color(255, 204, 204));
        lbngaygui.setText("Ngày gửi:");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lbnguoigui, javax.swing.GroupLayout.PREFERRED_SIZE, 699, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbchude, javax.swing.GroupLayout.PREFERRED_SIZE, 756, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addComponent(lbngaygui, javax.swing.GroupLayout.PREFERRED_SIZE, 622, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(lbnguoigui)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addComponent(lbchude)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbngaygui)
                .addContainerGap())
        );

        jPanel7.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        teanoidungmail.setColumns(20);
        teanoidungmail.setRows(5);
        jScrollPane2.setViewportView(teanoidungmail);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE)
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        taiFile.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        bttaifile.setBackground(new java.awt.Color(255, 255, 255));
        bttaifile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-save.png"))); // NOI18N
        bttaifile.setText("  Tải file");
        bttaifile.setCursor(new java.awt.Cursor(java.awt.Cursor.NW_RESIZE_CURSOR));
        bttaifile.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        bttaifile.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        bttaifile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttaifileActionPerformed(evt);
            }
        });

        tenFile.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        tenFile.setForeground(new java.awt.Color(0, 0, 255));
        tenFile.setText("Tên file:");

        javax.swing.GroupLayout taiFileLayout = new javax.swing.GroupLayout(taiFile);
        taiFile.setLayout(taiFileLayout);
        taiFileLayout.setHorizontalGroup(
            taiFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, taiFileLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(tenFile, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bttaifile)
                .addGap(36, 36, 36))
        );
        taiFileLayout.setVerticalGroup(
            taiFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, taiFileLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(taiFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bttaifile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tenFile))
                .addContainerGap())
        );

        javax.swing.GroupLayout loadnoidungLayout = new javax.swing.GroupLayout(loadnoidung);
        loadnoidung.setLayout(loadnoidungLayout);
        loadnoidungLayout.setHorizontalGroup(
            loadnoidungLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loadnoidungLayout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(loadnoidungLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(taiFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(downLoadFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        loadnoidungLayout.setVerticalGroup(
            loadnoidungLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loadnoidungLayout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(taiFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(downLoadFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jMenuBar1.setBackground(new java.awt.Color(153, 255, 255));
        jMenuBar1.setPreferredSize(new java.awt.Dimension(76, 30));

        jbtlaythu.setBackground(new java.awt.Color(204, 204, 255));
        jbtlaythu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon_homea[1].png"))); // NOI18N
        jbtlaythu.setText("Lấy thư");
        jbtlaythu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jbtlaythuMouseClicked(evt);
            }
        });
        jMenuBar1.add(jbtlaythu);

        jbtsoanthu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/256px-Email_Shiny_Icon.svg.png"))); // NOI18N
        jbtsoanthu.setText("Soạn thư mới");
        jMenuBar1.add(jbtsoanthu);

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/images.jpg"))); // NOI18N
        jMenu1.setText("Thiết lập giao diện");
        jMenu1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jMenu1ItemStateChanged(evt);
            }
        });

        UIPlasticXP.setText("PlasticXP");
        UIPlasticXP.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                UIPlasticXPItemStateChanged(evt);
            }
        });
        UIPlasticXP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UIPlasticXPActionPerformed(evt);
            }
        });
        jMenu1.add(UIPlasticXP);

        UIPlastic3D.setText("Plastic3D");
        UIPlastic3D.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                UIPlastic3DItemStateChanged(evt);
            }
        });
        jMenu1.add(UIPlastic3D);

        UIPlastic.setText("Plastic");
        jMenu1.add(UIPlastic);

        UIWindows.setText("Windown");
        UIWindows.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                UIWindowsItemStateChanged(evt);
            }
        });
        jMenu1.add(UIWindows);

        jMenuBar1.add(jMenu1);

        jbttrogiup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/howto.png"))); // NOI18N
        jbttrogiup.setText("Trợ giúp");

        jMenuItem1.setText("Tác giả");
        jbttrogiup.add(jMenuItem1);

        jMenuItem2.setText("Hướng dẫn");
        jbttrogiup.add(jMenuItem2);

        jMenuBar1.add(jbttrogiup);

        jbtthoatchuongtrinh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/delete1.png"))); // NOI18N
        jbtthoatchuongtrinh.setText("Thoát chương trình");
        jbtthoatchuongtrinh.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jbtthoatchuongtrinhMouseClicked(evt);
            }
        });
        jMenuBar1.add(jbtthoatchuongtrinh);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(loadnoidung, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(loadnoidung, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
  /* 
   private void  loadMail ()
    {
           
        
        try {
            out.println("Bắt đầu load mail");
            /*for(int i =1;i<5;i++){
               modelHopThuDen.addRow (new String []{
                                    "Chủ đề" ,
                                   " Người gữi" ,
                                    "Tóm tắt nội dung" ,
                                     "Ngày gữi" ,
                                        "Kích thước" ,
                                          "Tính trạng" , 
                                });
            }
            
            Properties properties = new Properties();
            properties.put("mail.pop3.host", mailPop3Host);
            Session emailSession = Session.getDefaultInstance(properties);
            POP3Store emailStore = (POP3Store) emailSession.getStore(mailStoreType);   
            emailStore.connect(mailPop3Host,mailUser, mailPassword);
          
           
            out.println("Kết nối thành công...");
        
            Folder emailFolder = emailStore.getFolder("INBOX");   
            emailFolder.open(Folder.READ_ONLY);
      
            out.println("Đang nạp hộp thư đến...");
            Message[] messages = emailFolder.getMessages();
            System.out.print(messages.length);
          
            for (int i = 0; i < messages.length; i++) {
		Message message = messages[i];
             modelHopThuDen.addRow (new String []{
                                  message.getSubject().toString(),
                                  message.getFrom()[0].toString(),
                                  message.getFileName(),
                                  message.getContent().toString() ,
                                  message.getDisposition(),
                                  message.getSentDate().toString(),
                                        "108KB",// kích thước
                                  message.isSet(Flags.Flag.SEEN) ? "Đã đọc" : "Chưa đọc" 
                                });
            
            }
          
            emailFolder.close(false);
            emailStore.close();
        } catch (Exception e) {
        }
            
                       
        
    }
*/
       private static  String nameFile ="";
        private static    boolean ktFile=false;
    public void readMultipartMail( ){
         for (; loadHopThuDen.getRowCount() > 0;) {
           loadHopThuDen.removeRow(0);
        }
             try {
                 
            Properties properties = System.getProperties();
            Session session = Session.getDefaultInstance(properties);
            Store store = session.getStore("pop3");
            store.connect(ConnectionServer.mailHost, ConnectionServer.kiemTraDiaChiGmail(ConnectionServer.userName),ConnectionServer.passWord);
            Folder folder = store.getFolder("inbox");
             if (!folder.exists()) {
            System.out.println("Không có hợp thư đến...");
            System.exit(0);
                           } 
             folder.open(Folder.READ_WRITE);
                unReadMessge =  folder.getUnreadMessageCount(); 

             Message[] msg = folder.getMessages();
         if(msg.length>0){
        for (int i = 0; i < msg.length; i++) {
            System.out.println("------------ Message " + (i + 1) + " ------------");
          //  String from = InternetAddress.toString(msg[i].getFrom());
            String from = InternetAddress.toString(msg[i].getRecipients(Message.RecipientType.BCC));
            
            if (from != null) {
                System.out.println("From: " + from);
            }

            String replyTo = InternetAddress.toString(msg[i].getReplyTo());// người đã gữi cái thư này tới
            if (replyTo != null) {
                System.out.println("Reply-to: " + replyTo);
            }
            
            String to = InternetAddress.toString( msg[i].getRecipients(Message.RecipientType.TO));// người nhận mail
            if (to != null) {
                System.out.println("To: " + to);
            }
            String size = msg[i].getSize()+" Kb";
            String subject = msg[i].getSubject();// tiêu đề của thư
            if (subject != null) {
                System.out.println("Subject: " + subject);
            }
            Date sent = msg[i].getSentDate(); // ngày gữi thư 
            if (sent != null) {
                System.out.println("Sent: " + sent.getDate());
            }

          int tinhtrang=  msg[i].isSet(Flags.Flag.SEEN) ?  1 : 0 ;// 1 đã đọc,0 chưa đọc
      
         
            System.out.println("Message : ");
          
            Multipart multipart = (Multipart) msg[i].getContent();
            String a = "";// đổ toàn bộ content
        
            for (int x = 0; x < multipart.getCount(); x++) {
                BodyPart bodyPart = multipart.getBodyPart(x);

                String disposition = bodyPart.getDisposition();

                if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
                    System.out.println("Mail have some attachment : ");
                    
                    DataHandler handler = bodyPart.getDataHandler();
                nameFile = handler.getName();
                    System.out.println("file name : " + handler.getName());
                } else {
                    a=(String) bodyPart.getContent();
                    System.out.println(bodyPart.getContent());
                }
            }
            if(tinhtrang ==0){
               //  JOptionPane.showConfirmDialog(null,"Bạn có "+ unReadMessge +"chưa đọc !","Thông báo",JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE);
            loadHopThuDen.addRow(new Object[]{nameFile,"<html><body><b>"+subject+"</html></body></b>",replyTo,to,a,sent,size}); // load từng mail lên jtable
        }// thư chưa đọc
            else 
          {
              // JOptionPane.showConfirmDialog(null,"Bạn có "+ unReadMessge +"chưa đọc !","Thông báo",JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE);
            loadHopThuDen.addRow(new Object[]{nameFile,subject,replyTo,to,a,sent}); // load từng mail lên jtable
          
          }// thư đã đọc rồi
            
        }
          bthopthuden.setText("Hộp thư đến ("+unReadMessge+")");
        folder.close(true);
        store.close();
        
     //   JOptionPane.showConfirmDialog(null,"Bạn có  "+ unReadMessge +" chưa đọc !","Thông báo",JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE);
    }
      else {
        System.out.println("Không có thư");
      }
        
        
        
        
        } catch (Exception e) {
            e.printStackTrace();
               JOptionPane.showConfirmDialog(this, "Không kết nối được","Thông báo",JOptionPane.YES_OPTION);
        }



    }// đọc mail dưới dạng mutipart
  
   
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
           //  JOptionPane.showConfirmDialog(null, "Mail đã được gữi đi","Thông báo",JOptionPane.YES_OPTION);
                  this.setLocationRelativeTo(null);
           //   loadMail();
               
    }//GEN-LAST:event_formWindowOpened

    private void jbtthoatchuongtrinhMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbtthoatchuongtrinhMouseClicked
        // TODO add your handling code here:
     int c = JOptionPane.showConfirmDialog(this, "Ứng dụng sẽ đóng trong 30s..!", "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == JOptionPane.YES_OPTION) {
                 System.exit(30);
            }
            else{
                this.setVisible(true);
            }
       
    }//GEN-LAST:event_jbtthoatchuongtrinhMouseClicked

    private void btsoanthuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btsoanthuActionPerformed
        // TODO add your handling code here:
      //  btsoanthu.setEnabled(false);
        Guimail guiMai = new Guimail();
        guiMai.setVisible(true);
        guiMai.setLocationRelativeTo(null);
        guiMai.setTitle("Soạn thư mới");
   
      //  this.setLocationRelativeTo(null);
    }//GEN-LAST:event_btsoanthuActionPerformed

    private void jbtlaythuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbtlaythuMouseClicked
        // TODO add your handling code here:
        // click chuôt
     
      readMultipartMail();
    }//GEN-LAST:event_jbtlaythuMouseClicked

    private void bthopthudenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bthopthudenActionPerformed
        // TODO add your handling code here:
          /* for (int i=0;i< loadHopThuDen.getRowCount();i++) {
            loadHopThuDen.removeRow(i);
                i++;
           }
           */
       
      readMultipartMail();
    }//GEN-LAST:event_bthopthudenActionPerformed
 public String trimspace(String str)
{
    str = str.replaceAll("\\s+", " ");
    str = str.replaceAll("(^\\s+|\\s+$)", "");
    return str;
}
    private void tbdsthuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbdsthuMouseClicked
        // TODO add your handling code here:
          int index= tbdsthu.getSelectedRow();
          if(  readMail.unReadMail(index)){
            
         
        lbchude.setText("<html><body> Chủ đề: <font color=black><b>"+trimspace(String.valueOf(tbdsthu.getValueAt(index, 1)))+ " </b></font></body></html>" );
        lbnguoigui.setText("Người gửi: " +String.valueOf(tbdsthu.getValueAt(index, 2)));
        lbngaygui.setText("Ngày gửi:"+trimspace(String.valueOf( tbdsthu.getValueAt(index, 5))));
        teanoidungmail.setText( String.valueOf(tbdsthu.getValueAt(index, 4)));
      String a= (String.valueOf(tbdsthu.getValueAt(index, 0)));
   
     //  readMultipartMail();
           
      if(a.length()>1){
          tenFile.setVisible(true);
          bttaifile.setVisible(true);
          bttaifile.setEnabled(true);
           downLoadFile.setVisible(true);
             downLoadFile.setStringPainted(true);
            downLoadFile.setBackground(Color.blue);
         tenFile.setText("Có 1 file đính kèm: "+a);
     
      }
      else {
      tenFile.setVisible(false);
          bttaifile.setVisible(false);
      }
          }
          else {
      JOptionPane.showConfirmDialog(this, "Lỗi", "Lỗi", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR);

          }
    }//GEN-LAST:event_tbdsthuMouseClicked

    private void btthoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btthoatActionPerformed
        // TODO add your handling code here:
        int c = JOptionPane.showConfirmDialog(this, "Ứng dụng sẽ đóng trong 30s..!", "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == JOptionPane.YES_OPTION) {
                 System.exit(30);
            }
            else{
                this.setVisible(true);
            }
    }//GEN-LAST:event_btthoatActionPerformed

    private void UIPlasticXPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UIPlasticXPActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_UIPlasticXPActionPerformed

    private void UIWindowsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_UIWindowsItemStateChanged
        // TODO add your handling code here:
         if (UIWindows.isSelected()) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                SwingUtilities.updateComponentTreeUI(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }//GEN-LAST:event_UIWindowsItemStateChanged

    private void UIPlasticXPItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_UIPlasticXPItemStateChanged
        // TODO add your handling code here:
        if (UIPlasticXP.isSelected()) {
            try {
                UIManager.setLookAndFeel(new com.jgoodies.plaf.plastic.PlasticXPLookAndFeel());
                SwingUtilities.updateComponentTreeUI(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_UIPlasticXPItemStateChanged

    private void UIPlastic3DItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_UIPlastic3DItemStateChanged
        // TODO add your handling code here:
      if (UIPlastic3D.isSelected()) {
            try {
                UIManager.setLookAndFeel(new com.jgoodies.plaf.plastic.Plastic3DLookAndFeel());
                SwingUtilities.updateComponentTreeUI(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_UIPlastic3DItemStateChanged

    private void jMenu1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jMenu1ItemStateChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenu1ItemStateChanged

    private void bttaifileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttaifileActionPerformed
        // TODO add your handling code here:
        /*
        JFileChooser jFileChooser = new JFileChooser();
          int c = jFileChooser.showSaveDialog(this);
            if (c == JFileChooser.CANCEL_OPTION) {
                tenFile.setText("");
            return;
           }
             if (c == JFileChooser.APPROVE_OPTION) {
          //  tenFile.setText("Đang tải file ............");
                  File file = jFileChooser.getSelectedFile();
             
             }*/
        bttaifile.setEnabled(false);
      
        downLoadFile.setValue(10);
         tenFile.setText("Đang tải file.......");
        //// int a = tbdsthu.getSelectedRow();
         try {
               downLoadFile.setValue(40);
             getFile.getFileOfMail(tbdsthu.getSelectedRow());
              downLoadFile.setValue(90);
              tenFile.setText("Tải file thành công.File được lưu ở : C:\\temp");
               downLoadFile.setValue(100);
                       MainLayer main = new MainLayer();
                      int open = JOptionPane.showConfirmDialog(null, "Tải file thành công.Lưu file C:\\temp","Thông báo",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                   /*    if(open==JOptionPane.YES_OPTION){
                       //     JList list = new JList("C:\\temp");
                            
                          JFileChooser jFileChooser = new JFileChooser();
                         int c = jFileChooser.showOpenDialog(this);
                           if (c == JFileChooser.APPROVE_OPTION) {
                            File file =jFileChooser.getSelectedFile();
                              file.canExecute();
                              file.setExecutable(true);
                             file.canRead();
                             file.setReadOnly();
                             file.setReadable(true);
                            
           }
                             
                                      
                           
                       }*/
         } catch (Exception e) {
             e.printStackTrace();
           tenFile.setText("Quá trình tải file đã xảy ra lỗi...");
        }
        
            
    }//GEN-LAST:event_bttaifileActionPerformed

    
    private void btxoathuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btxoathuActionPerformed
        // TODO add your handling code here:
      
          int b = JOptionPane.showConfirmDialog(this, "Bạn có chắc sẽ xóa mail này..?", "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
         if(b==JOptionPane.YES_OPTION){
        int xoa = tbdsthu.getSelectedRow();
       // loadHopThuDen.removeRow(xoa);
        if(deleteMail.deleteMail(xoa)){
       int a= JOptionPane.showConfirmDialog(this, "Mail đã được xóa.!", "Thông báo", JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE);
        readMultipartMail();
        }
        else {
        int a= JOptionPane.showConfirmDialog(this, "Mail không xóa được.!", "Lỗi", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
        }
         }
        
    }//GEN-LAST:event_btxoathuActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])throws Exception  {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainLayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainLayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainLayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainLayer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
   //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
              UIManager.put("swing.boldMetal", Boolean.FALSE); 
                new MainLayer().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem UIPlastic;
    private javax.swing.JMenuItem UIPlastic3D;
    private javax.swing.JMenuItem UIPlasticXP;
    private javax.swing.JMenuItem UIWindows;
    private javax.swing.JButton bthopthuden;
    private javax.swing.JButton btsoanthu;
    private javax.swing.JButton bttaifile;
    private javax.swing.JButton btthoat;
    private javax.swing.JButton btxoathu;
    private javax.swing.JProgressBar downLoadFile;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JMenu jbtlaythu;
    private javax.swing.JMenu jbtsoanthu;
    private javax.swing.JMenu jbtthoatchuongtrinh;
    private javax.swing.JMenu jbttrogiup;
    private javax.swing.JLabel lbchude;
    private javax.swing.JLabel lbngaygui;
    private javax.swing.JLabel lbnguoigui;
    private javax.swing.JPanel loadnoidung;
    private javax.swing.JPanel taiFile;
    private javax.swing.JTable tbdsthu;
    private javax.swing.JTextArea teanoidungmail;
    private javax.swing.JLabel tenFile;
    // End of variables declaration//GEN-END:variables
}
